// login.js
const regeneratorRuntime = require('../../lib/runtime');
const Api = require('../../utils/api.js');
const wx = require('../../lib/wx');
const wxapp = require('../../lib/wxapp');
const Util = require('../../utils/util.js');

// 获取应用实例
const app = getApp();
Page({
  data: {
    mobile: '',
    smsBtnText: '获取验证码',
    countdown: 60,
    autoFocus: true,
    isLogin:false
  },

  goToMe: function goToMe() {
    wx.reLaunch({ url: '../me/me' });
    return ;
  },

  goToMenu: wxapp.handler(function* goToMenu(next, e){
    const url = e.currentTarget.dataset.url;
    wx.reLaunch({
      url,
    });

    yield next;
  }),

  phoneLogin: wxapp.handler(function* phoneLogin(next, e) {
    const formProperties = e.detail.value;
    const phone = formProperties.phone;
    const mobileRule = new RegExp(/^1[3|4|5|7|8|9]\d{9}$/);
    const code = formProperties.mobileCode;
    if (phone === '') {
      wx.showToast({
        title: '请输入手机号码',
        image: '../../images/error.png',
        duration: 2000,
      });
      return;
    } else if (phone !== undefined && !mobileRule.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        image: '../../images/error.png',
        duration: 2000,
      });
      return;
    } else if (code === '') {
      wx.showToast({
        title: '请输入验证码',
        image: '../../images/error.png',
        duration: 2000,
      });
      return;
    }

    var that = this;
    var login = Api.login();
    var authTokenKey = Util.authTokenKey();
    var userInfo = wx.getStorageSync('wx_user_info');
  //console.log(userInfo);
    wx.request({
      url: login,
      header: {
        'content-type':'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: {
        mobile:phone,
        code:code,
        open_id:wx.getStorageSync('wxOpenID'),
        user_info:JSON.stringify(userInfo)//userInfo//JSON.parse(userInfo)
      },
      complete: function (res) {
        if(res.data.status == 1){
          // 将token存入缓存
          wx.setStorageSync(authTokenKey, res.data.data);
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000,
          });
          setTimeout(() => {
            wx.hideToast();
            that.goToMe();
          }, 3000);
        }else{
          wx.showToast({
            title: res.data.msg,
            image: '../../images/error.png',
            duration: 2000,
          });
        }
      }
    });


    

    yield next;
  }),
  bindGetUserInfo: function (e) {
    var that = this;
    //此处授权得到userInfo
    console.log(e.detail.userInfo);
    //接下来写业务代码
    var wxUserInfoKey = Util.wxUserInfo();
    wx.setStorageSync(wxUserInfoKey, e.detail.userInfo);

    wx.login({
      complete:function(res){
        if(res.code){
          that.getSessionKey(res.code);
        }
      }
    });
    // this.openidLogin();
    //最后，记得返回刚才的页面
    //wx.navigateBack({
    //  delta: 1
    //})
  },
  openidLogin :function(){
    var login4OpenId = Api.login4OpenId();
    var that = this;
    wx.request({
      url: login4OpenId,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: {
        open_id: wx.getStorageSync('wxOpenID')
      },
      complete: function (res) {
        if (res.data.status) {
          // 将token存入缓存
          wx.setStorageSync('auth_token_cache_key', res.data.data);
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000,
          });
          setTimeout(() => {
            wx.hideToast();
            that.goToMe();
          }, 3000);
        }else{
          that.setData({
            isLogin:true
          });
          console.log(that.data);
        }
      }
    });
  },

  sendSmsCode: wxapp.handler(function* sendSmsCode(next) {
    const mobile = this.data.mobile;
    const mobileRule = new RegExp(/^1[3|4|5|7|8]\d{9}$/);
    if (mobile === '') {
      wx.showToast({
        title: '手机号不能为空',
        image: '../../images/error.png',
        duration: 2000,
      });
      return;
    } 
    // else if (!mobileRule.test(mobile)) {
    //   wx.showToast({
    //     title: '请输入正确的手机号',
    //     image: '../../images/error.png',
    //     duration: 2000,
    //   });
    //   return;
    // }
    var that = this;
    var getSmsCode = Api.getSmsCode();console.log(getSmsCode);
    wx.request({
      url: getSmsCode,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: {
        mobile: mobile
      },
      complete: function (res) {
        console.log(res);
        if(res.data.status == 1){
          that.btnCountDown();
        }else{
          wx.showToast({
            title: res.data.msg,
            image: '../../images/error.png',
            duration: 2000,
          });
        }
      }
    });


    

    yield next;
  }),

  btnCountDown() {
    this.onTimer();
  },

  onTimer() {
    let countdown = this.data.countdown;
    countdown -= 1;
    if (countdown >= 0) {
      this.setData({
        countdown,
        smsBtnText: `${countdown}秒后重新获取`,
        smsBtnDis: true,
        btnDisabled: false,
        isCaptcha: false,
      });
      setTimeout(() => {
        this.onTimer();
      }, 1000);
    } else {
      this.setData({
        smsBtnDis: false,
        smsBtnText: '获取验证码',
        countdown: 60,
      });
    }
  },

  inputCode: wxapp.handler(function* inputCode(next, e) {
    this.setData({
      mobile: e.detail.value,
    });

    yield next;
  }),

  onShow: wxapp.handler(function* onShow(next) {
    //接下来写业务代码
    var wxUserInfoKey = Util.wxUserInfo();
    var userInfo = wx.getStorageSync(wxUserInfoKey);

    if(userInfo){
      this.setData({
        isLogin: true
      });
    }
    if(wx.getStorageSync('auth_token_cache_key')){
      this.goToMe();
    }
    yield next;
  }),

  onLoad: wxapp.handler(function* onLoad(next) {

    yield next;
  }),
  getSessionKey: function(code) {
    var getSessionKey = Api.getSessionKey();
    var that = this;
    if (!wx.getStorageSync('auth_token_cache_key')) {
      wx.request({
        url: getSessionKey,
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        method: 'POST',
        data: {
          code: code
        },
        complete: function (res) {
          if (!res.data.status) {
            wx.setStorageSync('wxOpenID', res.data.openid);
            wx.setStorageSync('wxSessionKey', res.data.session_key);
            that.openidLogin();
          }
        }
      });
    }
  }
});
